package filter;

import javax.servlet.*;
import java.io.IOException;
import java.util.Enumeration;

public class HspFilterConfig implements Filter {
    private String ip;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("HspFilterConfig init() 被调用..");
        String filterName = filterConfig.getFilterName();
        ip = filterConfig.getInitParameter("ip");
        ServletContext servletContext = filterConfig.getServletContext();
        Enumeration<String> initParameterNames = filterConfig.getInitParameterNames();
        while(initParameterNames.hasMoreElements()){
            System.out.println("名字"+initParameterNames.nextElement());
        }
        System.out.println("filterName= " + filterName);
        System.out.println("ip= " + ip);
        System.out.println("servletContext= " + servletContext);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String remoteAddr = servletRequest.getRemoteAddr();
        if (remoteAddr.contains(ip)){
            System.out.println("该网段被封杀");
            servletRequest.getRequestDispatcher("/login.jsp").
                    forward(servletRequest,servletResponse);
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
